package com.yuexin.project.scan.controller;

import com.google.common.collect.Maps;
import com.yuexin.common.utils.security.ShiroUtils;
import com.yuexin.framework.aspectj.lang.enums.DataSourceType;
import com.yuexin.framework.datasource.DynamicDataSourceContextHolder;
import com.yuexin.framework.web.controller.BaseController;
import com.yuexin.framework.web.domain.AjaxResult;
import com.yuexin.project.abutment.domain.Company;
import com.yuexin.project.abutment.mapper.AbutmentMapper;
import com.yuexin.project.order.domain.ManagerUser;
import com.yuexin.project.order.domain.MealsSetting;
import com.yuexin.project.order.mapper.CookUserMapper;
import com.yuexin.project.order.mapper.ManagerUserMapper;
import com.yuexin.project.order.mapper.MealsSettingMapper;
import com.yuexin.project.statistic.bookDish.service.IBookDishService;
import com.yuexin.project.system.user.domain.User;
import com.yuexin.project.system.user.service.IUserService;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 扫码 信息操作处理
 *
 * @author yuexin
 * @date 2018-10-22
 */
@Controller
@RequestMapping("/scan/qrcode")
public class ScanController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(ScanController.class);
    private String prefix = "scan/qrcode";
    @Autowired
    private MealsSettingMapper mealsSettingMapper;
    @Autowired
    private AbutmentMapper abutmentMapper;
    @Autowired
    private IUserService userService;
    @Autowired
    private ManagerUserMapper managerUserMapper;
    @Autowired
    private CookUserMapper cookUserMapper;
    @Autowired

    @GetMapping()
    public String code() {
        return prefix + "/codeLogin";
    }

    @PostMapping("/checkCompany")
    @ResponseBody
    @ApiOperation("检查公司账号是否存在")
    public AjaxResult firstLogin(String companyAccount) {
        Company comp = abutmentMapper.selectCompanyByAccount(companyAccount);
        Map<String, String> map = Maps.newHashMap();
        if (comp == null) {
            return error("公司账号不存在");
        }
        String companyIp = comp.getCompanyIp();
        String companyPort = comp.getCompanyPort();
        String status = comp.getStatus();
        map.put("companyAccount", companyAccount);
        map.put("companyIp", companyIp);
        map.put("companyPort", companyPort);
        map.put("orgName", comp.getOrgName());
        map.put("status", status);
        return success(map);
    }

    @PostMapping("/login")
    @ResponseBody
    public AjaxResult firstRealLogin(String loginName, String loginPwd, String companyAccount, HttpServletResponse response) throws InterruptedException {
        //判断用户是否有登录后台权限
        User user = userService.selectUserByLoginName(loginName);
        if (user != null) {
            ManagerUser managerUser = new ManagerUser();
            Integer sysuserId = user.getUserId().intValue();
            managerUser.setUserId(sysuserId);
            List<ManagerUser> managerUserList = managerUserMapper.selectManagerUserList(managerUser);
            if (managerUserList == null || managerUserList.size() <= 0) {
                // 用户无权限进入订餐后台
                return error(5,"您无权限进入订餐管理系统");
            }
        }
        DynamicDataSourceContextHolder.setDateSoureType(DataSourceType.SLAVE.name());
        Company comp = abutmentMapper.selectCompanyByAccount(companyAccount);
        String compId = comp.getCompId();
        DynamicDataSourceContextHolder.clearDateSoureType();
        DynamicDataSourceContextHolder.setDateSoureType(DataSourceType.MASTER.name());
        List<Long> cookUserIds = cookUserMapper.selectCookUserIdByCompanyId(compId);
        if(!cookUserIds.contains(user.getUserId())){
            return error(5,"您无权限进入订餐管理系统");
        }
        User isUser = new User();
        isUser.setCompanyId(compId);
        isUser.setLoginName(loginName);
        List<User> userList = userService.selectUserList(isUser);
        // 用户不存在或已被删除
        if (userList == null || userList.size() <= 0) {
            return error(1,"用户不存在或已被删除");
        }
        // 您的账号已被删除
        if ("2".equals(user.getDelFlag())) {
            return error(2,"您的账号已被删除");
        }
        // 您的账号已被禁用
        if ("1".equals(user.getStatus())) {
            return error(3,"您的账号已被禁用,若有需要,请联系管理员哦");
        }
        UsernamePasswordToken oaToken = new UsernamePasswordToken(loginName, loginPwd, "");
        SecurityUtils.getSubject().login(oaToken);
        SecurityUtils.getSubject().getSession().setTimeout(-1000L);
        User oauser = userService.selectUserByLoginName(loginName);
        ShiroUtils.setCompanyId(oauser.getCompanyId());
        return success();
    }

    private AjaxResult reurnResult(String url, HttpServletResponse response) {
        try {
            response.sendRedirect(url);
        } catch (IOException e) {
            log.error("登录失败：", e);
            reurnResult("/meals/abutment/errorpage?status=4", response);
        }
        return success();
    }

    public void get() {

//		bookDishService.selectBookDishByBookId(Lists.newArrayList(item.getBookId())));
    }

	@GetMapping("/logout")
    @ResponseBody
	public AjaxResult logout() {
        SecurityUtils.getSubject().logout();
        return AjaxResult.success("退出成功");
	}

    /**
     * 二维码页面
     */
    @GetMapping("/qrcode")
    public String qrcode() {
        return prefix + "/qrcode";
    }

    /**
     * 二维码页面
     */
    @GetMapping("/scan")
    public String scan() {
        return prefix + "/scan";
    }

    @GetMapping("/getCompanyName")
    @ResponseBody
    public AjaxResult getCompanyName() {
        Company company = abutmentMapper.selectCompanyByCompanyId(ShiroUtils.getCompanyId());
        return success(company);
    }

}
